<?php

namespace addons\oss;

use app\common\library\Menu;
use think\Addons;
use addons\oss\library\Util;
/**
 * 插件
 */
class Oss extends Addons
{

    /**
     * 插件安装方法
     * @return bool
     */
    public function install()
    {
        
        return true;
    }

    /**
     * 插件卸载方法
     * @return bool
     */
    public function uninstall()
    {
        
        return true;
    }

    /**
     * 插件启用方法
     * @return bool
     */
    public function enable()
    {
        
        return true;
    }

    /**
     * 插件禁用方法
     * @return bool
     */
    public function disable()
    {
        
        return true;
    }

    /**
     * 加载配置
     */
    public function uploadConfigInit(&$upload)
    {
        $config = $this->getConfig();
        if ($config['uploadmode'] === 'client')
        {
            $upload = [
                'uploadurl' => "http://{$config['bucket']}.{$config['endpoint']}",
                'cdnurl'    => $config['cdnurl'],
                'expire'    => $config['expire_time'],
                'bucket'    => $config['bucket'],
                'maxsize'   => $config['maxsize'],
                'mimetype'  => $config['mimetype'],
                'multipart' => [],
                'multiple'  => $config['multiple'] ? true : false,
                'storage'   => 'oss'
            ];
        }
        else
        {
            $upload = array_merge($upload, [
                // 'uploadurl' => url("addons/oss/Index")."/upload",
                'maxsize'    => $config['maxsize'],
                'mimetype'   => $config['mimetype'],
                'multiple'   => $config['multiple'] ? true : false,
            ]);
        }
    }

    /**
     * 上传成功后
     */
    public function uploadAfter($attachment)
    {
        // die( $attachment->url );
        $config = $this->getConfig();
        if ($config['uploadmode'] === 'server')
        {
            $file = ROOT_PATH . 'public' .$attachment->url;

            try{

                $Util = new Util($config);

                $save = $Util->saveToOss(urldecode($file));

                if( !$config['savetolocal'] )
                {
                    $attachment->delete();

                    @unlink($file);

                    exit( json_encode(['code' => 1, 'msg' => __('Upload successful'), "data"=>['url' => $save] ],JSON_UNESCAPED_UNICODE) );
                }                

            }catch(\Exception $e)
            {
                $attachment->delete();

                @unlink($file);

                exit( json_encode(['code' => 0, 'msg' => '无法上传到远程服务器，错误:' . $e->getMessage()],JSON_UNESCAPED_UNICODE) );
            }        
        }
    }

    /**
     * 删除成功后
     */
    public function uploadDelete($attachment)
    {
        $config = $this->getConfig();
        $Util = new Util($config);
        $file = ROOT_PATH . 'public' . str_replace('/', DIRECTORY_SEPARATOR, $attachment->url);
        $Util->delFormOss($file);
    }

}
